package com.wf.ew.webService;

import com.wf.ew.orderB.model.Bill;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class JKXHttp {

    public static void main(String[] args) {
        JKXHttp.getBillList();
        System.exit(0);
    }

    public static List<Bill> getBillList() {
        List<Bill> list = new ArrayList<Bill>();
        try {
            String rvalue;
            String apikey = "api_12228", apisecret = "8307dac2b9f0d7689b11418e696ff1e0";
            rvalue = executeGet("http://service.cttms.com/api_service/services/OrderService/token?apiKey=" + apikey
                    + "&apiSecret=" + apisecret);
            System.out.println(rvalue);
            rvalue = getToken(rvalue);
            rvalue = executeGet("http://service.cttms.com/api_service/services/OrderService/preExecute?token=" + rvalue
                    + "&jsonString={\"pageIndex\":1,\"pagesize\":200}}");

            rvalue = rvalue.replaceAll("<ns:preExecuteResponse xmlns:ns=\"http://www.cttms.com\"><ns:return>","");
            rvalue = rvalue.replaceAll("</ns:return></ns:preExecuteResponse>","");
            System.out.println(rvalue);

            JSONObject jb = JSONObject.fromObject(rvalue);
            JSONObject data = jb.getJSONObject("data");
            JSONArray orders = data.getJSONArray("orders");
            Bill b = null;

            for(int i=0;i<orders.size();i++){
                JSONObject job = orders.getJSONObject(i);   // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                String appointTime = job.getString("appointTime");
                String appointDate = job.getString("appointDate");
                String customerShortName = job.getString("customerShortName");
                String address = job.getString("address");
                String containerType = job.getString("containerType");
                String bookingNo = job.getString("bookingNo");
                String containerNo = job.getString("containerNo");
                String truck = job.getString("truck");
                String driverMobile = job.getString("driverMobile");
                String identifyingCode = job.getString("identifyingCode");
                String ship = job.getString("ship");
                String voyage = job.getString("voyage");
                String sealNo = job.getString("sealNo");
                String telephone = job.getString("telephone");
                String busiId = job.getString("busiId");//业务编号
                String getConPile = job.getString("getConPile");//提箱
                String returnConPile = job.getString("returnConPile");//进港码头
                b = new Bill();
                b.setCustomer(customerShortName);
                b.setPackDate(appointDate);
                b.setFactoryAddress(address);
                b.setBoxType(containerType);
                b.setBillOfLading(bookingNo);
                b.setBoxNum(containerNo);
                b.setCarNo(truck);
                b.setDriverPhone(driverMobile);
                b.setSerialno(identifyingCode);
                b.setVessel(ship);
                b.setVoyage(voyage);
                b.setSealno(sealNo);
                b.setContactsPhone(telephone);
                b.setBusiId(busiId);
                b.setGetConPile(getConPile);
                b.setReturnConPile(returnConPile);
                list.add(b);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    private static String getToken(String rvalue) {
        JSONObject json = null;
        try {
            Document doc = DocumentHelper.parseText(rvalue);
            Element e = (Element) doc.getRootElement().elements().get(0);
            rvalue = e.getTextTrim();
            json = JSONObject.fromObject(rvalue);
        }catch (Exception e) {
            e.printStackTrace();
        }
        if (json != null && json.containsKey("token")) {
            return json.getString("token");
        } else {
            System.out.println(rvalue);
        }
        return null;
    }

    public static String executeGet(String urlStr) throws Exception {
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        HttpGet get = null;
        HttpEntity entity = null;
        String rvalue = "";

        try {
            client = HttpClients.createDefault();
            URL url = new URL(urlStr);
            String hostAnPort = "";
            if (url.getPort() != -1) {
                hostAnPort = url.getHost() + ":" + url.getPort();
            } else {
                hostAnPort = url.getHost();
            }
            URI uri = new URI(url.getProtocol(), hostAnPort, url.getPath(), url.getQuery(), null);
            get = new HttpGet(uri);

            // 开始发送
            client = HttpClients.createDefault();
            long l = System.currentTimeMillis();
            response = client.execute(get);
            System.out.println("耗时：" + (System.currentTimeMillis() - l) / 1000.0);
            entity = response.getEntity();
            // 获取结果
            rvalue = EntityUtils.toString(entity, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return rvalue;
    }
}
